import {
  createRouter,
  createWebHashHistory,
  RouteRecordRaw,
  Router,
} from "vue-router";
import Login from "../views/login/Login.vue";
import { IfoApi } from "../request/api";
import { useStore } from "../store/login";
import { ElMessage } from "element-plus";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: Login,
  },
  {
    path: "/",
    redirect: "/index",
  },
  {
    path: "/home",
    name: "home",
    component: () => import("../views/home/Home.vue"),
  },
  {
    path: "/",
    component: () => import("../views/home/Home.vue"),
    children: [
      {
        path: "index",
        component: () => import("../views/index/index.vue"),
      },
    ],
  },
];

const router: Router = createRouter({
  routes,
  history: createWebHashHistory(),
});

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem("token");
  const store = useStore();

  // 数据库里面的没有数据且存在token才能请求数据
  if (store.menus.length === 0 && token) {
    IfoApi().then((res) => {
      if (res.data.code === 200) {
        //   console.log(res.data.data.menus);
        store.menus = res.data.data.menus;
        store.username = res.data.data.username;
        store.rotes.forEach((item) => {
          const route: RouteRecordRaw = {
            path: "/" + item.name,
            name: item.name,
            component: () => import("../views/home/Home.vue"),
            meta: {
              // 在meta里面把对应的中文存起来，然后在路由里面获取，以生成面包屑的中文
              title: item.title,
            },
            children: item.children?.map((items) => ({
              path: items.name,
              name: items.name,
              component: () =>
                import(`../views/${item.name}/${items.name}.vue`),
              meta: {
                title: items.title,
              },
            })),
          };
          if (item.children[0]) {
            route.redirect = `/${item.name}/${item.children[0].name}`;
            console.log(123123123123123123);
          }
          router.addRoute(route);
          next(to.fullPath);
        });
      } else if (!token && to.path !== "/login") {
        ElMessage.error("请求先登录");
        next("/login");
      }
      // 如果已经登录，不能直接通过url回到登陆页
      else if (token && store.menus.length !== 0 && to.path === "/login") {
        ElMessage.warning("请先退出登录再重新登录");
        // 不让用户访问登录页 ， 跳转回原来的页面
        next(from.fullPath);
      }
    });
  } else {
    next();
  }
});
export default router;
